/*
 * jlb
 */
package com.jlb.miner.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.jlb.active.dao.ActivePoolDAO;
import com.jlb.active.dao.ActiveRecordDAO;
import com.jlb.active.entity.ActiveRecord;
import com.jlb.core.base.BaseDAO;
import com.jlb.core.base.BaseSVImpl;
import com.jlb.core.entity.Page;
import com.jlb.core.enums.YNEnum;
import com.jlb.core.exceptions.BaseException;
import com.jlb.core.exceptions.MinerItemException;
import com.jlb.core.exceptions.UserActiveException;
import com.jlb.core.tools.StringTools;
import com.jlb.core.tools.security.Md5;
import com.jlb.count.entity.Count;
import com.jlb.count.service.CountSV;
import com.jlb.jlb.dao.JlbOreLogDAO;
import com.jlb.jlb.entity.JlbOreLog;
import com.jlb.jlb.entity.JlbOreLogEvent;
import com.jlb.jlb.entity.JlbOreLogType;
import com.jlb.miner.dao.MinerItemDAO;
import com.jlb.miner.entity.MinerItem;
import com.jlb.miner.entity.MinerItemState;
import com.jlb.miner.entity.PayType;
import com.jlb.platform.entity.PlatformAccount;
import com.jlb.setting.dao.SettingDAO;
import com.jlb.setting.entity.Setting;
import com.jlb.star.dao.StarLevelDAO;
import com.jlb.user.dao.*;
import com.jlb.user.entity.*;
import com.jlb.user.service.UserSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("minerItemSV")
@Slf4j
public class MinerItemSVImpl extends BaseSVImpl<MinerItem, Long> implements MinerItemSV {

    @Autowired
    private MinerItemDAO minerItemDAO;

    @Resource
    private UserSV userSV;

    @Resource
    private UserMinerDAO userMinerDAO;

    @Resource
    private StarLevelDAO starLevelDAO;

    @Resource
    private UserJlbDAO userJlbDAO;

    @Resource
    private UserOreDAO userOreDAO;

    @Resource
    private UserActiveDAO userActiveDAO;

    @Resource
    private ActiveRecordDAO activeRecordDAO;

    @Resource
    private UserMinerWorkRecordDAO userMinerWorkRecordDAO;

    @Resource
    private UserPurchaseMinerRecordDAO userPurchaseMinerRecordDAO;

    @Resource
    private SettingDAO settingDAO;

    @Resource
    private CountSV countSV;

    @Resource
    private JlbOreLogDAO jlbOreLogDAO;

    @Resource
    private ActivePoolDAO activePoolDAO;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return minerItemDAO;
    }

    /**
     * 保存account对象
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    public void save(MinerItem entity) throws BaseException {
        entity.setCode(String.valueOf(uidGenerator.getUID()));
        entity.setState(MinerItemState.Sales.name());
        super.save(entity);
    }

    /**
     * 加载一个对象MinerItem
     *
     * @param id * @param code 编码
     * @return MinerItem
     */
    @Override
    public MinerItem load(java.lang.Long id, java.lang.String code) {
        if (id == null && code == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return minerItemDAO.load(param);
    }

    /**
     * 加载一个对象MinerItem 通过id
     *
     * @param id
     * @return MinerItem
     */
    @Override
    public MinerItem loadById(java.lang.Long id) {
        if (id == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        return minerItemDAO.loadById(id);
    }

    /**
     * 加载一个对象MinerItem 通过code
     *
     * @param code 编码
     * @return MinerItem
     */
    @Override
    public MinerItem loadByCode(java.lang.String code) {
        if (code == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        return minerItemDAO.loadByCode(code);
    }


    /**
     * 根据主键id,oldStates 共同更新 MinerItem 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(java.lang.Long id, MinerItemState newState, MinerItemState... oldStates) {
        if (id == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        if (newState == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        if (oldStates == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        minerItemDAO.updateStateById(id, new Date(), newState, oldStates);
    }

    /**
     * 根据主键code,oldStates 共同更新 MinerItem 的状态到newState状态
     *
     * @param code      编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateByCode(java.lang.String code, MinerItemState newState, MinerItemState... oldStates) {
        if (code == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        if (newState == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        if (oldStates == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        minerItemDAO.updateStateByCode(code, new Date(), newState, oldStates);
    }

    /**
     * 根据主键id 更新 MinerItem 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
    public void updateById(java.lang.Long id, MinerItemState state) {
        if (id == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        minerItemDAO.updateById(id, state, new Date());
    }

    /**
     * 根据主键code 更新 MinerItem 的状态到另一个状态
     *
     * @param code  编码
     * @param state 状态
     */
    @Override
    public void updateByCode(java.lang.String code, MinerItemState state) {
        if (code == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        minerItemDAO.updateByCode(code, state, new Date());
    }


    /**
     * 删除对象MinerItem
     *
     * @param id * @param code 编码
     * @return MinerItem
     */
    @Override
    public void delete(java.lang.Long id, java.lang.String code) {
        if (id == null && code == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        minerItemDAO.delete(param);
    }


    /**
     * 查询MinerItem分页
     *
     * @param minerItem 对象
     * @param offset    查询开始行
     * @param limit     查询行数
     * @return List<MinerItem>
     */
    @Override
    public List<MinerItem> list(MinerItem minerItem, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = null;
        if (minerItem != null) {
            map = JSON.parseObject(JSON.toJSONString(minerItem, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return minerItemDAO.list(map, new RowBounds(offset, limit));
    }

    @Override
    public int count(MinerItem minerItem) {
        Map<String, Object> map = null;
        if (minerItem != null) {
            map = JSON.parseObject(JSON.toJSONString(minerItem, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return minerItemDAO.count(map);
    }

    /**
     * 查询MinerItem分页
     *
     * @param id     * @param code  编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<MinerItem>
     */
    @Override
    public List<MinerItem> list(java.lang.Long id, java.lang.String code, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return minerItemDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(java.lang.Long id, java.lang.String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return minerItemDAO.count(param);
    }

    /**
     * 购买矿机
     * 1.查看用户是否存在,查询用户是否已经有矿机
     * 2.查看矿机状态
     * 3.查看用户金兰宝，矿石数量，激活币是否具备
     * 4.为用户创建矿机
     * 5.为用户启动矿机挖矿，创建金兰宝挖矿中
     * 6.记录购买日志
     *
     * @param minerCode   矿机编码
     * @param userCode    账户
     * @param payType     支付类型
     * @param pinPassword
     */
    @Override
    public void purchase(String minerCode, String userCode, String payType, String pinPassword) {
        //1.查看用户是否存在
        User user = userSV.loadByCode(userCode);
        if (user == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.User_Error);
        }
        //用户是否正常
        if (UserState.Active != UserState.getEnum(user.getState())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.User_Not_Active);
        }
        //密码是否正确
        if (!Md5.md5(pinPassword).equals(user.getPinPassword())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Pin_Password_Is_Error);
        }
        //是否已经购买过矿机
        UserMiner userMiner = userMinerDAO.loadByUserCode(user.getCode());
        if (userMiner != null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Already_Buy);
        }

        //2.查看矿机状态
        MinerItem minerItem = minerItemDAO.loadByCode(minerCode);
        if (minerItem == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Mill_Not_Exist);
        }
        if (MinerItemState.Sales != MinerItemState.getEnum(minerItem.getState())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Miner_Not_Sales);
        }


        //3.查看用户金兰宝，矿石数量，激活币是否具备
        this.jlbOrOreIsEnough(user, minerItem, payType, JlbOreLogEvent.Purchase);
        //激活币是否足够
        StringBuffer sb = new StringBuffer("用户：" + user.getAccount() + "购买了编号为：" + minerItem.getCode() + "的矿机");
        if (PayType.Jlb == PayType.getEnum(payType)) {
            this.activeIsEnough(user, minerItem, sb.toString(), minerItem.getActive());
        } else {
            this.activeIsEnough(user, minerItem, sb.toString(), minerItem.getMixActive());
        }

        //4.为用户创建矿机
        UserJlb userJlb = user.getUserJlb();
        if (userJlb == null) {
            userJlb = new UserJlb();
            userJlb.setUserCode(user.getCode());
            userJlb.setState(UserJlbState.Active.name());
            userJlb.setJlb(0);
            userJlb.setRelease(0);
            userJlb.setDigInTotalJlb(0);
            userJlb.setDigInJlb(minerItem.getDailyIncome());
            userJlb.setDigInJlbState(UserJlbMinerState.Dig_In.name());
            userJlbDAO.insert(userJlb);
        } else {
            userJlb.setDigInTotalJlb(0);
            userJlb.setDigInJlb(minerItem.getDailyIncome());
            userJlb.setDigInJlbState(UserJlbMinerState.Dig_In.name());
            userJlbDAO.update(userJlb);
        }

        //记录用户购买的矿机
        userMiner = StringTools.convertObject(minerItem, UserMiner.class);
        userMiner.setId(null);
        userMiner.setUserCode(userCode);
        userMiner.setMinerCode(minerItem.getCode());
        userMiner.setState(UserMinerState.Working.name());
        userMiner.setCreateTime(new Date());
        userMiner.setUpdateTime(new Date());
        userMinerDAO.insert(userMiner);

        if (minerItem.getInventory() > 0) {
            minerItem.setInventory(minerItem.getInventory() - 1);
            if (minerItem.getInventory() == 0) {
                minerItem.setState(MinerItemState.Sell_Out.name());
            }
            minerItemDAO.update(minerItem);
        }

        //5.为用户启动矿机挖矿，创建金兰宝挖矿中
        UserMinerWorkRecord userMinerWorkRecord = new UserMinerWorkRecord();
        userMinerWorkRecord.setUserCode(user.getCode());
        userMinerWorkRecord.setMinerCode(minerItem.getCode());
        userMinerWorkRecord.setJlb(minerItem.getDailyIncome());
        userMinerWorkRecord.setState(UserMinerWorkRecordState.Dig_In.name());
        userMinerWorkRecord.setCreateTime(new Date());
        userMinerWorkRecordDAO.insert(userMinerWorkRecord);

        //6.记录购买日志
        UserPurchaseMinerRecord userPurchaseMinerRecord = new UserPurchaseMinerRecord();
        userPurchaseMinerRecord.setCode(uidGenerator.getUID() + "");
        userPurchaseMinerRecord.setMinerCode(minerItem.getCode());
        userPurchaseMinerRecord.setUserCode(user.getCode());
        userPurchaseMinerRecord.setPower(minerItem.getPower());
        userPurchaseMinerRecord.setType(UserPurchaseMinerRecordState.Purchase.name());
        userPurchaseMinerRecord.setCreateTime(new Date());
        userPurchaseMinerRecordDAO.insert(userPurchaseMinerRecord);
    }

    /**
     * 升级矿机
     * 1.查看用户是否存在
     * 2.查看矿机状态
     * 3.查看用户金兰宝，矿石数量，激活币是否具备
     * 4.为用户升级矿机
     * 5.更新金兰宝挖矿日收益
     * 6.记录升级日志
     *
     * @param minerCode   矿机编码
     * @param userCode    账户
     * @param payType     支付类型
     * @param pinPassword 支付密码
     */
    @Override
    public void upgrade(String minerCode, String userCode, String payType, String pinPassword) {
        //1.查看用户是否存在
        User user = userSV.loadByCode(userCode);
        if (user == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.User_Error);
        }
        //判断用户状态
        if (UserState.Active != UserState.getEnum(user.getState())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.User_Not_Active);
        }
        //密码是否正确
        if (!Md5.md5(pinPassword).equals(user.getPinPassword())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Pin_Password_Is_Error);
        }
        //查询用户是否已经有矿机
        UserMiner userMiner = userMinerDAO.loadByUserCode(user.getCode());
        if (userMiner == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Mill_Not_Exist);
        }

        //2.查看矿机状态
        MinerItem minerItem = minerItemDAO.loadByCode(minerCode);
        if (minerItem == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Mill_Not_Exist);
        }
        //判断矿机状态
        if (MinerItemState.Sales != MinerItemState.getEnum(minerItem.getState())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Miner_Not_Sales);
        }

        //3.查看用户金兰宝，矿石数量，激活币是否具备
        this.jlbOrOreIsEnough(user, minerItem, payType, JlbOreLogEvent.Upgrade);
        //激活币是否足够
        StringBuffer sb = new StringBuffer("用户：" + user.getAccount() + ",从编号为" + userMiner.getMinerCode() + "的矿机，升级为编号：" + minerItem.getCode() + "的矿机");
        String jlbOreRate = null;
        String[] arrays = null;
        Integer activeRate = null;
        if (PayType.Jlb == PayType.getEnum(payType)) {
            jlbOreRate = settingDAO.loadByK(Setting.Key.Jlb_Rate.name()).getV();
            arrays = jlbOreRate.split(":");
            activeRate = Integer.valueOf(arrays[1]);
        } else {
            jlbOreRate = settingDAO.loadByK(Setting.Key.Jlb_Ore_Rate.name()).getV();
            arrays = jlbOreRate.split(":");
            activeRate = Integer.valueOf(arrays[2]);
        }

        MinerItem minerItemFlag = minerItemDAO.loadByCode(userMiner.getMinerCode());
        int price = Integer.valueOf(minerItem.getPrice()) - Integer.valueOf(minerItemFlag.getPrice());
        BigDecimal rateDecimal = new BigDecimal(activeRate).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_UP);
        int refiningNum = rateDecimal.multiply(new BigDecimal(price)).intValue();
        this.activeIsEnough(user, minerItem, sb.toString(), refiningNum);

        // 4.为用户升级矿机
        userMiner.setMinerCode(minerCode);
        userMiner.setDailyIncome(minerItem.getDailyIncome());
        userMiner.setPower(minerItem.getPower());
        userMiner.setMultiple(minerItem.getMultiple());
        userMiner.setUpperLimit(minerItem.getUpperLimit());
        userMiner.setUpdateTime(new Date());
        userMinerDAO.update(userMiner);
        if (minerItem.getInventory() > 0) {
            minerItem.setInventory(minerItem.getInventory() - 1);
            if (minerItem.getInventory() == 0) {
                minerItem.setState(MinerItemState.Sell_Out.name());
            }
            minerItemDAO.update(minerItem);
        }

        // 5.更新金兰宝挖矿日收益
        UserJlb userJlb = user.getUserJlb();
        userJlb.setDigInJlb(minerItem.getDailyIncome());
        userJlb.setDigInJlbState(UserJlbMinerState.Dig_In.name());
        userJlbDAO.update(userJlb);

        // 6.记录购买记录
        UserPurchaseMinerRecord userPurchaseMinerRecord = new UserPurchaseMinerRecord();
        userPurchaseMinerRecord.setCode(uidGenerator.getUID() + "");
        userPurchaseMinerRecord.setMinerCode(minerItem.getCode());
        userPurchaseMinerRecord.setUserCode(user.getCode());
        userPurchaseMinerRecord.setPower(minerItem.getPower());
        userPurchaseMinerRecord.setType(UserPurchaseMinerRecordState.Upgrade.name());
        userPurchaseMinerRecord.setCreateTime(new Date());
        userPurchaseMinerRecordDAO.insert(userPurchaseMinerRecord);
    }

    /**
     * 复投矿机
     * 1.查看用户是否存在
     * 2.查看矿机状态
     * 3.查看用户金兰宝，矿石数量，激活币是否具备
     * 4.为用户复投矿机，激活矿机
     * 5.更新金兰宝挖矿状态，开始挖金兰宝
     * 6.记录复投日志
     *
     * @param userCode    账户
     * @param payType     支付类型
     * @param pinPassword
     */
    @Override
    public void recast(String userCode, String payType, String pinPassword) {
        //1.查看用户是否存在
        User user = userSV.loadByCode(userCode);
        if (user == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.User_Error);
        }
        //判断用户状态
        if (UserState.Active != UserState.getEnum(user.getState())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.User_Not_Active);
        }
        //支付密码是否正确
        if (!Md5.md5(pinPassword).equals(user.getPinPassword())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Pin_Password_Is_Error);
        }
        //查询用户是否已经有矿机
        UserMiner userMiner = userMinerDAO.loadByUserCode(user.getCode());
        if (userMiner == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Mill_Not_Exist);
        }
        //判断是否需要复投
        if (UserMinerState.Working == UserMinerState.getEnum(userMiner.getState())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Not_Need_Re_Cast_Miner);
        }

        //2.查看矿机状态
        MinerItem minerItem = minerItemDAO.loadByCode(userMiner.getMinerCode());
        if (minerItem == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Mill_Not_Exist);
        }
        //判断矿机状态
        if (MinerItemState.Sales != MinerItemState.getEnum(minerItem.getState())) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Miner_Not_Sales);
        }

        //3.查看用户金兰宝，矿石数量，激活币是否具备
        jlbOrOreIsEnough(user, minerItem, payType, JlbOreLogEvent.Re_Cast_Miner);
        //激活币是否足够
        StringBuffer sb = new StringBuffer("用户：" + user.getAccount() + "复投了编号为：" + minerItem.getCode() + "的矿机");
        if (PayType.Jlb == PayType.getEnum(payType)) {
            this.activeIsEnough(user, minerItem, sb.toString(), minerItem.getActive());
        } else {
            this.activeIsEnough(user, minerItem, sb.toString(), minerItem.getMixActive());
        }

        // 4.为用户复投矿机，激活矿机
        userMiner.setState(UserMinerState.Working.name());
        userMiner.setUpdateTime(new Date());
        userMinerDAO.update(userMiner);

        // 5.更新金兰宝挖矿日收益
        UserJlb userJlb = user.getUserJlb();
        userJlb.setDigInTotalJlb(0);
        userJlb.setDigInJlb(minerItem.getDailyIncome());
        userJlb.setDigInJlbState(UserJlbMinerState.Dig_In.name());
        userJlbDAO.update(userJlb);

        // 6.记录升级日志
        UserPurchaseMinerRecord userPurchaseMinerRecord = new UserPurchaseMinerRecord();
        userPurchaseMinerRecord.setCode(uidGenerator.getUID() + "");
        userPurchaseMinerRecord.setMinerCode(minerItem.getCode());
        userPurchaseMinerRecord.setUserCode(user.getCode());
        userPurchaseMinerRecord.setPower(minerItem.getPower());
        userPurchaseMinerRecord.setType(UserPurchaseMinerRecordState.Re_Cast.name());
        userPurchaseMinerRecord.setCreateTime(new Date());
        userPurchaseMinerRecordDAO.insert(userPurchaseMinerRecord);
    }

    /**
     * 查看用户金兰宝，矿石数量
     *
     * @param user      用户信息
     * @param minerItem 矿机信息
     * @param payType   支付方式
     * @return
     */
    private void jlbOrOreIsEnough(User user, MinerItem minerItem, String payType, JlbOreLogEvent state) {
        //只使用金兰宝购买
        UserJlb platformJlb = userJlbDAO.loadByCode(PlatformAccount.PlatformAccountEnum.Platform.name());//获取公司金兰宝账户信息
        if (PayType.Jlb == PayType.getEnum(payType)) {
            //是否是升级,升级只需要补差价
            int jlb = minerItem.getJlb();
            if (state == JlbOreLogEvent.Upgrade) {
                String jlbOreRate = settingDAO.loadByK(Setting.Key.Jlb_Rate.name()).getV();
                String[] arrays = jlbOreRate.split(":");
                Integer jlbRate = Integer.valueOf(arrays[0]);
                UserMiner userMiner = userMinerDAO.loadByUserCode(user.getCode());
                MinerItem minerItemFlag = minerItemDAO.loadByCode(userMiner.getMinerCode());
                int price = Integer.valueOf(minerItem.getPrice()) - Integer.valueOf(minerItemFlag.getPrice());
                BigDecimal rateDecimal = new BigDecimal(jlbRate).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_UP);
                jlb = rateDecimal.multiply(new BigDecimal(price)).setScale(0, BigDecimal.ROUND_UP).intValue();
                if (jlb <= 0) {
                    throw new MinerItemException(BaseException.BaseExceptionEnum.Just_Allow_Upgrade);
                }
            }
            //金兰宝是否足够
            if (user.getUserJlb() == null) {
                throw new MinerItemException(BaseException.BaseExceptionEnum.Jlb_Not_Enough_Error);
            }
            if (user.getUserJlb().getJlb() < jlb) {
                throw new MinerItemException(BaseException.BaseExceptionEnum.Jlb_Not_Enough_Error);
            }
            //修改用户金兰宝数量
            UserJlb userJlb = user.getUserJlb();
            userJlb.setJlb(userJlb.getJlb() - jlb);
            userJlbDAO.update(userJlb);
            //userJlbDAO.updateToReduce(user.getCode(), jlb);
            //记录统计数据
            countSV.saveOrUpdate(new Count(null, String.valueOf(jlb), null, null));
            //平台账户接收
            platformJlb.setJlb(platformJlb.getJlb() + jlb);
            userJlbDAO.update(platformJlb);
            //记录日志变化
            jlbOreLogDAO.insert(new JlbOreLog(user.getCode(), PlatformAccount.PlatformAccountEnum.Platform.name(),
                    jlb, JlbOreLogType.JLB.name(), state.name(), user.getUserJlb().getJlb() + jlb,
                    user.getUserJlb().getJlb(), platformJlb.getJlb() - jlb, platformJlb.getJlb()));
        } else if (PayType.Jlb_Ore == PayType.getEnum(payType)) {//使用金兰宝+矿石购买
            //是否是升级,升级只需要补差价
            int mixJlb = minerItem.getMixJlb();
            int mixOre = minerItem.getMixOre();
            if (state == JlbOreLogEvent.Upgrade) {
                String jlbOreRate = settingDAO.loadByK(Setting.Key.Jlb_Ore_Rate.name()).getV();
                String[] arrays = jlbOreRate.split(":");
                Integer jlbRate = Integer.valueOf(arrays[0]);
                Integer oreRate = Integer.valueOf(arrays[1]);
                UserMiner userMiner = userMinerDAO.loadByUserCode(user.getCode());
                MinerItem minerItemFlag = minerItemDAO.loadByCode(userMiner.getMinerCode());
                int price = Integer.valueOf(minerItem.getPrice()) - Integer.valueOf(minerItemFlag.getPrice());
                BigDecimal jlbRateDecimal = new BigDecimal(jlbRate).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_UP);
                mixJlb = jlbRateDecimal.multiply(new BigDecimal(price)).intValue();
                BigDecimal oreRateDecimal = new BigDecimal(oreRate).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_UP);
                mixOre = oreRateDecimal.multiply(new BigDecimal(price)).setScale(0, BigDecimal.ROUND_UP).intValue();
                if (mixJlb <= 0 || mixOre <= 0) {
                    throw new MinerItemException(BaseException.BaseExceptionEnum.Just_Allow_Upgrade);
                }
            }
            //金兰宝是否足够
            if (user.getUserJlb() == null) {
                throw new MinerItemException(BaseException.BaseExceptionEnum.Jlb_Not_Enough_Error);
            }
            if (user.getUserJlb().getJlb() < mixJlb) {
                throw new MinerItemException(BaseException.BaseExceptionEnum.Jlb_Not_Enough_Error);
            }
            //矿石是否足够
            if (user.getUserOre() == null) {
                throw new MinerItemException(BaseException.BaseExceptionEnum.Ore_Not_Enough_Error);
            }
            if (user.getUserOre().getOre() < mixOre) {
                throw new MinerItemException(BaseException.BaseExceptionEnum.Ore_Not_Enough_Error);
            }
            //修改用户金兰宝数量
            UserJlb userJlb = user.getUserJlb();
            userJlb.setJlb(userJlb.getJlb() - mixJlb);
            userJlbDAO.update(userJlb);
            //userJlbDAO.updateToReduce(user.getCode(), mixJlb);
            //平台账户接收金兰宝
            platformJlb.setJlb(platformJlb.getJlb() + mixJlb);
            userJlbDAO.update(platformJlb);
            //记录统计数据
            countSV.saveOrUpdate(new Count(null, String.valueOf(mixJlb), null, String.valueOf(mixJlb)));
            //记录日志变化
            jlbOreLogDAO.insert(new JlbOreLog(user.getCode(), PlatformAccount.PlatformAccountEnum.Platform.name(),
                    mixJlb, JlbOreLogType.JLB.name(), state.name(), user.getUserJlb().getJlb() + mixJlb,
                    user.getUserJlb().getJlb(), platformJlb.getJlb() - mixJlb, platformJlb.getJlb()));

            //修改用户矿石数量
            userOreDAO.updateToReduce(user.getCode(), mixOre);
            //记录统计数据
            countSV.saveOrUpdate(new Count(null, null, null, String.valueOf(mixOre)));
            //平台账户接收矿石
            UserOre platformOre = userOreDAO.loadByUserCode(PlatformAccount.PlatformAccountEnum.Platform.name());
            platformOre.setOre(platformOre.getOre() + mixOre);
            userOreDAO.update(platformOre);
            //记录矿石转账日志
            jlbOreLogDAO.insert(new JlbOreLog(user.getCode(), PlatformAccount.PlatformAccountEnum.Platform.name(),
                    mixOre, JlbOreLogType.ORE.name(), state.name(), user.getUserOre().getOre() + mixOre,
                    user.getUserOre().getOre(), platformOre.getOre() - mixOre, platformOre.getOre()));
        }
    }

    /**
     * 激活币是否足够
     *
     * @param user      用户信息
     * @param minerItem minerItem
     * @param summary   备注
     * @param num       数量
     */
    private void activeIsEnough(User user, MinerItem minerItem, String summary, int num) {
        //激活币是否足够
        if (YNEnum.Y == YNEnum.getYN(minerItem.getIsActiveCoin())) {
            Map<String, Object> param = new HashMap<>();
            param.put("userCode", user.getCode());
            UserActive userActive = userActiveDAO.load(param);
            if (userActive == null) {
                userActiveDAO.insert(new UserActive(user.getCode(), 0));
                throw new UserActiveException(BaseException.BaseExceptionEnum.Active_Not_Enough_Error);
            }

            if (userActive.getActive() < num) {
                throw new UserActiveException(BaseException.BaseExceptionEnum.Active_Not_Enough_Error);
            }

            userActive.setActive(userActive.getActive() - num);
            userActiveDAO.update(userActive);

            //添加记录
            activeRecordDAO.insert(new ActiveRecord(String.valueOf(num), user.getCode(), summary));
        }
    }

    /**
     * 修改状态
     *
     * @param minerCode 矿机编码
     * @param state     矿机状态
     */
    @Override
    public void updateState(String minerCode, MinerItemState state) {
        if (StringTools.isEmpty(minerCode)) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        if (state == null) {
            throw new MinerItemException(BaseException.BaseExceptionEnum.Ilegal_Param);
        }
        Map<String, Object> params = new HashedMap();
        params.put("code", minerCode);
        params.put("state", state.name());
        minerItemDAO.update(params);

    }

    /**
     * 查询用户可升级到的矿机
     * 1.查询用户的矿机
     * 2.查询产量大于该矿机的所有矿机
     *
     * @param userCode 用户编码
     * @return List<MinerItem>
     */
    @Override
    public List<MinerItem> listForUpgrade(String userCode) {
        UserMiner userMiner = userMinerDAO.loadByUserCode(userCode);
        Map<String, Object> params = new HashedMap();
        params.put("state", MinerItemState.Sales.name());
        params.put("state", MinerItemState.Sales.name());
        params.put("state", MinerItemState.Sales.name());
        return null;
    }

}
